package com.framework.common.util;

import com.framework.common.Enums.FrameworkErrorCodeEnum;
import com.framework.common.exception.BusinessException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/5/4 11:03
 * @since JDK 1.8
 */
public class ValidateUtil {

    /**
     * 厘金额格式校验
     *
     * @param amount
     *            金额
     */
    public static boolean isAmountLi(String amount) {
        Pattern pattern = Pattern.compile("^[0-9]\\d*$");
        Matcher match = pattern.matcher(amount);
        if (!match.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 验证非零的正整数
     *
     * @param 待验证的字符串
     * @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean IsIntNumber(String amount) {
        Pattern pattern = Pattern.compile("^\\+?[1-9][0-9]*$");
        Matcher match = pattern.matcher(amount);
        if (!match.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 必填参数校验
     *
     * @param objMap
     *            被校验参数
     * @param args
     *            必填参数列表
     */
    public static boolean requiredFieldsChk(Map<?, ?> objMap, String[] args) {
        for (String arg : args) {
            if (null == objMap.get(arg) || "".equals(objMap.get(arg))) {
                throw new BusinessException(FrameworkErrorCodeEnum.PARAM_ERROR, arg);
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 必填参数校验
     *
     * @param obj
     *            被校验bean
     * @param args
     *            必填参数列表
     */
    public static void requiredFieldsChk(Object obj, String[] args) {
        Map<String, Object> paramsMap = null;
        try {
            paramsMap = PropertyUtils.describe(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        for (String arg : args) {
            if (null == paramsMap.get(arg) || "".equals(paramsMap.get(arg))) {
                throw new BusinessException(FrameworkErrorCodeEnum.PARAM_ERROR, arg);
            }
        }
    }

    /**
     * 开始日期 结束日期校验
     *
     * @param startDate
     * @param endDate
     */
    public static void checkStartDateAndEndDate(String startDate, String endDate) {
        if (StringUtils.isNotBlank(endDate)) {
            SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
            try {
                if (sd.parse(endDate).compareTo(sd.parse(startDate)) <= 0) {
                    throw new BusinessException(FrameworkErrorCodeEnum.END_DATE_EARLY_THAN_START_DATE);
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
